package com.example.axon;


import com.example.axon.commands.*;
import com.example.axon.events.SubtractEvent;
import com.example.axon.events.TransferFinishEvent;
import com.example.axon.events.TransferOutEvent;
import com.example.axon.utils.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.modelling.saga.EndSaga;
import org.axonframework.modelling.saga.SagaEventHandler;
import org.axonframework.modelling.saga.StartSaga;
import org.axonframework.spring.stereotype.Saga;

import javax.annotation.Resource;

import static org.axonframework.modelling.command.AggregateLifecycle.apply;

@Saga
@Slf4j
public class AccountSaga {

    @Resource
    private CommandGateway commandGateway;
    private String id;
    private String userName;
    private String password;
    private String email;
    private Double balance;


    @StartSaga
    @SagaEventHandler(associationProperty = "txId")
    public void out(TransferOutEvent event) {
        log.info("TransferOutEvent saga. {}" ,event);
        TransferInCmd payload = JsonMapper.getInstance().convertValue(event, TransferInCmd.class);
        payload.setBalance(event.getAmount());
        payload.setAccountId(event.getToId());
        commandGateway.send(payload);

    }

    @SagaEventHandler(associationProperty = "txId")
    @EndSaga
    public void finished(TransferFinishEvent event) {
//        apply(JsonMapper.getInstance().convertValue(cmd, CreateEvent.class));
        log.info("TransferFinishEvent saga. {}" ,event);
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }
}
